package com.xuanzheng.company.servlet;

import com.google.gson.Gson;
import com.xuanzheng.company.entity.AIModel;
import com.xuanzheng.company.entity.User;
import com.xuanzheng.company.service.AIService;
import com.xuanzheng.company.service.impl.AIServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * AI模型管理Servlet
 */
@WebServlet("/aiModels")
public class AIModelsServlet extends HttpServlet {
    
    private final AIService aiService = new AIServiceImpl();
    private final Gson gson = new Gson();
    
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        
        response.setContentType("application/json;charset=UTF-8");
        response.setHeader("Cache-Control", "no-cache");
        
        PrintWriter out = response.getWriter();
        
        try {
            // 检查用户是否登录
            HttpSession session = request.getSession(false);
            if (session == null) {
                response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
                Map<String, Object> error = new HashMap<>();
                error.put("success", false);
                error.put("message", "请先登录");
                out.print(gson.toJson(error));
                return;
            }

            User user = (User) session.getAttribute("user");
            if (user == null) {
                response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
                Map<String, Object> error = new HashMap<>();
                error.put("success", false);
                error.put("message", "请先登录");
                out.print(gson.toJson(error));
                return;
            }
            
            List<AIModel> models;
            
            // 如果是管理员，返回所有模型；否则只返回启用的模型
            if (isAdmin(request)) {
                models = aiService.getAllModels();
            } else {
                models = aiService.getEnabledModels();
            }
            
            // 处理敏感信息，不返回API密钥
            models.forEach(model -> model.setApiKey("***"));
            
            out.print(gson.toJson(models));
            
        } catch (Exception e) {
            e.printStackTrace();
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            Map<String, Object> error = new HashMap<>();
            error.put("success", false);
            error.put("message", "服务器内部错误");
            // 修改这一行：使用gson.toJson()替代objectMapper.writeValueAsString()
            out.print(gson.toJson(error));
        }
        
        out.flush();
        out.close();
    }
    
    private boolean isAdmin(HttpServletRequest request) {
        HttpSession session = request.getSession(false);
        if (session == null) return false;
        
        User user = (User) session.getAttribute("user");
        return user != null && user.getRole() == 2; // 系统管理员
    }
}
